<template>
  <page-header-wrapper>
    <a-card>
      <a-row>
        <a-space>
          <a-button @click='getTemplate'>
            下载excel模板文件
          </a-button>
          <a-button @click='() => {visible=true}'>查看导入规则</a-button>
          <a-upload
            name='file'
            :multiple='false'
            accept='application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            :file-list='fileList'
            :before-upload='beforeUpload'
            :remove='handleRemove'
          >
            <a-button :loading='loading'> + 选择excel文件</a-button>
          </a-upload>
        </a-space>
      </a-row>
      
      <a-alert
        v-if='importStatus === 0'
        style='width: 700px;margin: 13px auto;'
        message='操作成功'
        :description='analysis'
        type='success'
        show-icon
      />
      
      <a-alert
        v-if='importStatus === 1'
        style='width: 700px;margin: 13px auto;'
        message='操作异常'
        :description='analysis'
        type='warning'
        show-icon
      />
      
      <a-divider style='margin-top: 30px;'>导入失败情况</a-divider>
      
      <!--失败表格-->
      <a-table
        ref='table'
        size='small'
        rowKey='errorRow'
        bordered
        :loading='loading'
        :columns='columns2'
        :data-source='errorList'
      >
        <div slot='status' slot-scope='status'>
          <a-tag color='red'>导入失败</a-tag>
        </div>
        
        <div slot='sysUserImportVo' slot-scope='sysUserImportVo'>
          <json-viewer :value='toJson(sysUserImportVo)'></json-viewer>
        </div>
      </a-table>
      
      <a-divider style='margin-top: 30px;'>导入成功情况</a-divider>
      <!--成功表格-->
      <a-table
        ref='table'
        size='small'
        rowKey='studentId'
        bordered
        :loading='loading'
        :columns='columns'
        :data-source='successList'
        :showPagination='false'
      >
        <span slot='status' slot-scope='status' style='cursor: pointer'>
          <a-tag color='green'>导入成功</a-tag>
      </span>
      </a-table>
    
    </a-card>
    
    <a-modal
      width='70%'
      :visible='visible'
      @ok='() => {visible=false}'
      @cancel='() => {visible=false}'
      title='校验规则'>
      <h2>默认账号: <span style='color: red'>学号</span></h2>
      <h2>默认密码: <span style='color: red'>学号后6位+姓名各首字母小写(全称)</span></h2>
      <br>
      <h1>校验规则如下</h1>
      <img src='@/views/newcomer/img/checkRule.png' alt='checkRule' />
      <h1>示例</h1>
      <img src='@/views/newcomer/img/excelDemo.png' alt='excelDemo' />
    </a-modal>
  
  </page-header-wrapper>
</template>

<script>
import { getImportCandidateTemplate, importCandidate } from '@/api/newcomer'
import FileSaver from 'file-saver'
import JsonViewer from 'vue-json-viewer'


const columns = [
  {
    title: '学号',
    width: 200,
    dataIndex: 'studentId',
    scopedSlots: { customRender: 'studentId' }
  },
  {
    title: '姓名',
    dataIndex: 'nickName',
    scopedSlots: { customRender: 'nickName' }
  },
  {
    title: '班级',
    dataIndex: 'clasz',
    scopedSlots: { customRender: 'clasz' }
  },
  {
    title: '手机号码',
    dataIndex: 'phonenumber',
    scopedSlots: { customRender: 'phonenumber' }
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    scopedSlots: { customRender: 'email' }
  },
  {
    title: '导入状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  }
]
const columns2 = [
  {
    title: '学号',
    width: 200,
    dataIndex: 'studentId',
    scopedSlots: { customRender: 'studentId' }
  },
  {
    title: '姓名',
    dataIndex: 'nickName',
    scopedSlots: { customRender: 'nickName' }
  },
  {
    title: '班级',
    dataIndex: 'clasz',
    scopedSlots: { customRender: 'clasz' }
  },
  {
    title: '手机号码',
    dataIndex: 'phonenumber',
    scopedSlots: { customRender: 'phonenumber' }
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    scopedSlots: { customRender: 'email' }
  },
  {
    title: '发送错误的行数',
    dataIndex: 'errorRow',
    scopedSlots: { customRender: 'errorRow' }
  },
  {
    title: '失败原因',
    dataIndex: 'errorMsg',
    scopedSlots: { customRender: 'errorMsg' }
  },
  {
    title: '导入状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  }
]
export default {
  name: 'ImportCandidate',
  components: {
    JsonViewer
  },
  data() {
    return {
      columns,
      columns2,
      loading: false,
      visible: false,
      fileList: [],
      successList: [],
      errorList: [],
      analysis: '',
      importStatus: -1
    }
  },
  created() {
  },
  methods: {
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      let curFile = this.fileList[0]
      // 判断是否为excel文件
      if (!/\.(xlsx|xls)$/.test(curFile.name)) {
        this.$message.error('请上传正确的excel文件')
        this.handleRemove(file)
        return
      }
      if (curFile.size > 1024 * 1024 * 5) {
        this.$message.error('文件大小不能超过5M')
        this.handleRemove(file)
        return
      }
      this.importCandidate()
      return false
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    getTemplate() {
      getImportCandidateTemplate().then((res) => {
        let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        FileSaver.saveAs(blob, '用户导入模板.xlsx')
        this.$message.success('导出成功')
      })
    },
    importCandidate() {
      let file = this.fileList[0]
      if (!file) {
        this.$message.error('请选择文件')
        return
      }
      this.loading = true
      importCandidate(file).then((res) => {
        this.successList = res.data.list
        console.log(res.data.list)
        console.log(res.data.errorList)
        this.errorList = res.data.errorList.map(item => {
          const { sysUserImportVo, errorRow, errorMsg } = item
          return {
            studentId: sysUserImportVo.studentId,
            clasz: sysUserImportVo.clasz,
            nickName: sysUserImportVo.nickName,
            phonenumber: sysUserImportVo.phonenumber,
            email: sysUserImportVo.email,
            errorRow,
            errorMsg
          }
        })
        this.analysis = res.data.analysis
        if (this.analysis.includes('很抱歉')) {
          this.importStatus = 1
        } else {
          this.importStatus = 0
        }
        this.fileList = []
        this.loading = false
      })
    },
    toJson(str) {
      if (this.isJSON(str)) {
        return JSON.parse(str)
      }
      return str
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          let obj = JSON.parse(str)
          return !!(typeof obj == 'object' && obj)
        } catch (e) {
          return false
        }
      }
    }
  }
}
</script>

<style scoped>

</style>